<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\facade\Config;
class Common extends Controller
{  
    protected $temp;
    public function initialize(){
      $this->temp=config('config.view_path').$this->getTemp();//获取默认模板文件夹名称
      $temp_src=config('config.tpl_replace_string.temp').$this->getTemp();//资源路径
      $menu=$this->getMenu();//导航
      $curr=input('id')?input('id'):'index';//栏目高亮
      $config=$this->getConf();//网站配置
      static $foot=[];//底部导航
      foreach ($menu as $k => $v) {
        if (!empty($v['son'])) {
          $foot[]=$v;
        }
      }
      $this->assign([
          'tsrc'    =>$temp_src,
          'menu'    =>$menu,
          'curr'    =>$curr,
          'config'  =>$config,
          'foot'    =>$foot,
      ]);
    }
    //获取模板
    public function getTemp(){
        $conf=db('config')->find();
        $temp=json_decode($conf['config'],true);
        return $temp['temp'];
    }
    //获取头部导航
    public function getMenu(){
      $cate=db('cate')->where(array('pid'=>0,'isshow'=>1))->select();
      foreach ($cate as $k => $v) {
        $cate[$k]['son']=db('cate')->where(array('pid'=>$v['id'],'isshow'=>1))->select();
      }
      return $cate;
    }
    //获取网站配置
    public function getConf(){
      $config=db('config')->find();
      $config=json_decode($config['config'],true);
      return $config;
    }
    // 面包屑导航
    public function getPos($cid){
      static $arr=array();
      if(empty($arr)){
        $arr[]=db('cate')->where('id',$cid)->field('id,pid,catename')->find();
      }
      $data=db('cate')->field('id,pid,catename')->select();
      $cate=db('cate')->where('id',$cid)->field('id,pid,catename')->find();
      foreach ($data as $k => $v) {
        if ($cate['pid']==$v['id']) {
          $arr[]=$v;
          $this->getPos($v['id']);
        }
        
      }
      return array_reverse($arr);
    }
      
    //获取顶级栏目id,用于当前栏目顶级栏目的高亮显示
    public function getTopId($cid){
      $data=db('cate')->field('id,pid')->select();
      // 查询后 将结果处理成 如下数组格式
      $arr=array();
      foreach ($data as $k => $v) {
          $arr[$v['id']]=$v['pid'];
      }
      $id = $cid;
      while($arr[$id]) {
          $id = $arr[$id];
      }
      return  $id; // 1
  }


}